<?php
/**
 * Created by PhpStorm.
 * User: 86151
 * Date: 2023/9/19
 * Time: 11:06
 */

namespace app\api\controller;
use app\admin\model\Wxpay;
use app\common\controller\Api;
use app\admin\model\Acxq as Acxqs;
use think\Config;
use think\Db;
use app\admin\model\Auth;
use think\Exception;
use app\admin\model\Index as IndexModel;
class Acxq extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 正常购买
     */
    public function acorder(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $operator_id = Db::name('operator')->where('name',$userInfo['operator'])->value('id');
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        $outOrderId = makeOrderNum();//本地订单
        $productSn =$datainfo['resource_id'];//商品编号
        $itemlist =  $datainfo['itemlist'];//规格id
        $quantity = 1;//数量
        $customerPhoneNumber  =  $datainfo['number'];//用户号码
        $goodsInfo = Db::name('goods')->where('item_id',$productSn)->find();
        $goods = Db::name('acgoods_sku')->where('sku_id',$itemlist)->where('item_id',$productSn)->find();
        if(!$goods){
            $this->error('商品信息不存在');
        }
        $inspect = Acxqs::inspect($productSn,$itemlist,$customerPhoneNumber,$outOrderId,$goods['sku_activity_price_cent']);
        if($inspect['code'] != 0){
            $this->error($inspect['msg']);
        }else{
            $original_price_cent = $goods['sku_original_price_cent'] * $quantity;//原价
            $activity_price_cent = $goods['sku_activity_price_cent'] * $quantity;//活动价
            $cbj =  round($goods['sku_settlement_price'] * $quantity / 100,2);
            $params = [
                'operator_id'=>$operator_id,
                'user_mobile'=>$customerPhoneNumber,
                'user_id'=>$userInfo['id'],
                'outer_order_id'=>$inspect['data']['order_sn'],
                'order_no'=>$outOrderId,
                'type'=>11,//爱吃商品
                'resource_id'=>$productSn,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$quantity,
                'title'=>$goods['sku_short_name'],
                'brand'=>$goodsInfo['title'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'price'=>$cbj,
            ];
            //是会员的话，打折
            $amount = $activity_price_cent;
            $amount = round($amount/100,2);//转为正常价格,因为数据库里存的是分
            $params['discount_amount'] = round($original_price_cent/100,2) - $amount;
            $params['amount'] = $amount;
            //创建并返回支付参数
            $id = Db::name("order")->insertGetId($params);
            if($id){
                //---微信支付---
                if($amount>0){
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$outOrderId
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/acpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error('创建订单失败!');
            }
        }
    }

    /**
     * 会员兑换购买
     */
    public function viporder(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $qinghai = 0; //会员五  青海类型
        //会员特殊购买
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 0;
        }
        $zone_id =$datainfo['zone_id'] ;
        $class_id =$datainfo['class_id'] ;
        if($sanfang){  //三方兑换验证
            $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
            if ($sanfang_vip) {
                if($sanfang_vip['is_att'] == 3){
                    $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            }else{
                exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
            }
        }else {
            if ($zone_id) {
                $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                if ($operator_vip['type'] == 5) {
                    $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            }
        }
        $outOrderId = makeOrderNum();//本地订单
        $productSn = $datainfo['resource_id'];//商品编号
        $itemlist =$datainfo['itemlist'];//规格id
        $quantity = 1;//数量
        $customerPhoneNumber  =$datainfo['number'];//用户号码
        if($userInfo['mobile'] != $customerPhoneNumber){
            $this->error("领取号码与注册号码不一致");
        }
        $goodsInfo = Db::name('goods')->where('item_id',$productSn)->find();
        $goods = Db::name('acgoods_sku')->where('sku_id',$itemlist)->where('item_id',$productSn)->find();
        $inspect = Acxqs::inspect($productSn,$itemlist,$customerPhoneNumber,$outOrderId,$goods['sku_activity_price_cent']);
        if($inspect['code'] != 0){
            $this->error($inspect['msg']);
        }else{
            if($zone_id) {
                $exchange_goods = Db::name('operator_exchange_goods')->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $productSn)->find();
                $original_price_cent = $exchange_goods['fsj'];//原价
                $activity_price_cent = $exchange_goods['vip_money'];//会员价价
                $from = 2;
            }
            if($activity_price_cent<=0){
                $this->error("流程错误");exit;
            }
            $cbj =  round($goods['sku_settlement_price'] * $quantity / 100,2);
            $params = [
                'user_mobile'=>$customerPhoneNumber,
                'user_id'=>$userInfo['id'],
                'outer_order_id'=>$inspect['data']['order_sn'],
                'order_no'=>$outOrderId,
                'type'=>11,//爱吃商品
                'resource_id'=>$productSn,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$quantity,
                'title'=>$goods['sku_short_name'],
                'brand'=>$goodsInfo['title'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'qing_id'=>$qinghai,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'from'=>$from,
                'exchange_code'=>'',
                'price'=>$cbj,
            ];
            $params['discount_amount'] = $original_price_cent - $activity_price_cent;
            $amount =$activity_price_cent;
            $params['amount'] = $amount;
            $id = Db::name("order")->insertGetId($params);
            if($id) {
                if ($amount > 0) {
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$outOrderId
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/acpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error('创建订单失败!');
            }
        }
    }

    /**
     * 兑换
     */
    public function exchange(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $qinghai  = 0; //青海类型
        //会员特殊购买
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        $zone_id = $datainfo['zone_id'];
        $class_id = $datainfo['class_id'];
        $codeex =$datainfo['codeex'];//爱音乐兑换
        $outOrderId = makeOrderNum();//本地订单
        $productSn = $datainfo['resource_id'];//商品编号
        $itemlist = $datainfo['itemlist'];//规格id
        $quantity = 1;//数量
        $customerPhoneNumber  = input('number');//用户号码
        if($userInfo['mobile'] != $customerPhoneNumber){
            $this->error("领取号码与注册号码不一致");
        }
        if($zone_id) {
            $exchange_goods = Db::name('operator_exchange_goods')->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $productSn)->find();
            $activity_price_cent = $exchange_goods['vip_money'];//会员价价
        }
        if($activity_price_cent>0){
            $this->error("流程错误");exit;
        }
        $goodsInfo = Db::name('goods')->where('item_id',$productSn)->find();
        $goods = Db::name('acgoods_sku')->where('sku_id',$itemlist)->where('item_id',$productSn)->find();
        $inspect = Acxqs::inspect($productSn,$itemlist,$customerPhoneNumber,$outOrderId,$goods['sku_activity_price_cent']);
        if($inspect['code'] != 0){
            $this->error($inspect['msg']);
        }else{
            $cbj =  round($goods['sku_settlement_price'] * $quantity / 100,2);
            $params = [
                'user_mobile'=>$customerPhoneNumber,
                'user_id'=>$userInfo['id'],
                'outer_order_id'=>$inspect['data']['order_sn'],
                'order_no'=>$outOrderId,
                'type'=>11,//爱吃商品
                'resource_id'=>$productSn,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$quantity,
                'title'=>$goods['sku_short_name'],
                'brand'=>$goodsInfo['title'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'exchange_code'=>$codeex,
                'price'=>$cbj,
            ];
            $amount = $goods['sku_original_price_cent'];
            $params['discount_amount'] = round($amount/100,2);
            $params['amount'] = 0;
            $id = 0;
            if($sanfang){  //三方兑换验证
                Db::startTrans();
                try {
                    $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
                    if ($sanfang_vip) {
                        if($sanfang_vip['is_att'] == 3){
                            $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id',$zone_id)->where('is_do',0)->where('end_time','>',time())->lock(true)->find();
                            if(!$qinghao){
                                Db::rollback();
                                exit(json_encode(array('code' =>0, 'msg' =>'会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id',$qinghao['id'])->update(['is_do'=>1]);
                            $qinghai = $qinghao['id'];
                        }
                    } else {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
                    }
                    $params['from'] = 2;
                    $id = Db::name("order")->insertGetId($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                }
            }else {
                if ($zone_id) {
                    Db::startTrans();
                    try {
                        $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                        if ($operator_vip['type'] == 5) {
                            $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->lock(true)->find();
                            if (!$qinghao) {
                                Db::rollback();
                                exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id', $qinghao['id'])->update(['is_do' => 1]);
                            $qinghai = $qinghao['id'];
                        }
                        $params['from'] = 2;
                        $id = Db::name("order")->insertGetId($params);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' => 0, 'msg' => $e), JSON_UNESCAPED_UNICODE));
                    }
                }
            }
            if($id) {
                $order = Db::name("order")->where('id',$id)->find();
                $res = Acxqs::createOrder($outOrderId);
                if($res['code'] == 0){
                    Db::startTrans();
                    try {
                        Db::name("order")->where(['order_no' => $outOrderId])->update(['status' => 2]);
                        Db::name('goods')->where('item_id', $order['resource_id'])->setInc('total_sales');
                        Db::name('goods')->where('item_id', $order['resource_id'])->setDec('stock');
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->success("获取成功",$strArr);
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    if($qinghai >0){
                        Db::name('qinghao')->where('id',$qinghai)->update(['is_do'=>0]);
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }
    }


    /**
     * 退款接口
     */
    public function refund(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $order_id =  input('order_id');
        $reason = input("reason");//退款原因
        if(!$order_id){
            $this->error('参数不全');
        }
        $order = Db::name("order")->where('id',$order_id)->find();
        if($order['from']==2){
            //兑换的订单不作退还
            $this->error("该订单属于会员专享兑换权益，不支持退换，详情请咨询在线客服：4008772758");
        }
        $res = Acxqs::refund($order['order_no']);
        if($res['code'] == 0){
            if($order['amount']>0){
                Wxpay::doRefund($order['amount'],$order['amount'],$order['order_no'],$order['transaction_id'],$reason);
            }
            Db::name('order')->where('id',$order_id)->update(['status'=>5,'rund_time'=>time(),'rund_info'=>$reason]);
            Db::name('voucher')->where('order_id',$order_id)->update(['voucher_status'=>'CANCELED']);
            $this->success('退款成功');
        }else{
            $this->error($res['msg']);
        }
    }


}